package com.mediacloud.app.newsmodule.fragment.simulcast

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.eventTrack.TXReportManager.Companion.getVisibility
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.model.component.ComponentItem
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.utils.ViewUtils
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.BuildConfig
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.component.BufferComponentContainer
import com.mediacloud.app.newsmodule.adaptor.component.ComponentHolder
import com.mediacloud.app.newsmodule.adaptor.component.IExposure
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.newsmodule.fragment.newslist.TXRecommendFragment
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.utils.ExposurePoolService.Companion.getExecutorService
import kotlinx.android.synthetic.main.fragment_simulcast.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*

/**
 * 联播
 */
class SimulcastFragment:HqyNavFragment(), OnRefreshLoadMoreListener,IExposure {
    var page = 1
    var simulcastAdapter : SimulcastAdapter?=null

    var catalogID: String? = null
    var catalogItem: CatalogItem? = null

    var chaitiao_cid :String?=null
    var zhengsheng_cid :String?=null

    var year = 0
    var month = 0
    var day = 0
    var todayStamp: Long = 0L
    var targetIndex = 0
    var starTime = 0L
    var endTime = 0L
    var targetTime = 0L
    var sdf = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)


    override fun getLayoutResID(): Int {
        return R.layout.fragment_simulcast
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        navPaddingTopMatch()
    }

    override fun initArgs() {
        super.initArgs()
        catalogItem = fragmentArguments.getParcelable("catalog")

        catalogItem?.navigate?.categoryChildren?.forEach {
            if (it.name == catalogItem?.catname) {
                catalogID = it.catid
                chaitiao_cid = it.chaitiao_cid//绑拆条栏目ID
                zhengsheng_cid = it.zhengsheng_cid//绑政声栏目ID
            }
        }

    }

    override fun initView() {
        loadingView = findViewById(R.id.mLoadingView)
        initStateView()
        showStateView(BaseBackActivity.TYPE_LOADING, false)

        freshLayout.setOnRefreshLoadMoreListener(this)
        val layoutManager =
            ViewUtils.generateRecyclerLinearLayoutManager(context, true)
        rvSimulcast.layoutManager = layoutManager
        simulcastAdapter = SimulcastAdapter()
        rvSimulcast.adapter = simulcastAdapter

        scroll.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            app_jhapp_home_subtab_content_imp()
        }
        simulcastAdapter?.onItemChildClickListener =
            BaseQuickAdapter.OnItemChildClickListener { adapter, view, position ->
                var item  = adapter.getItem(position) as SimulcastBean
                when(view.id){
                    R.id.imgLogo,R.id.ivPlay->{
                        val articleItem = ArticleItem()
                        val newsCastList = item.newsCastList[0]
                        articleItem.id = newsCastList.id
                        articleItem.type = newsCastList.type
                        articleItem.catalogId = newsCastList.catalogId
                        articleItem.logo = newsCastList.logo
                        articleItem.title = newsCastList.title
                        articleItem.publishdate_format = newsCastList.publishDate
                        articleItem.publishdate = newsCastList.publishDate
                        articleItem.referName = newsCastList.referName
                        articleItem.Author = newsCastList.author
                        articleItem.authorId = newsCastList.authorId
                        articleItem.authorNickName = newsCastList.authorNickName
                        CDPTrackReportManager.getInstance().NewsRPClick(position,articleItem)
                        NewsItemClickUtils.OpenItemNewsHandle(context,newsCastList.type,articleItem, catalogItem)
                    }
                    R.id.itemDate->{
                        openDateSelector()
                    }
                    R.id.tvZXMore->{
                        SimulcastMoreListActivity.openActivity(requireContext(),1,"$chaitiao_cid",item.dateTime,"")
                    }
                    R.id.tvZSMore->{
                        SimulcastMoreListActivity.openActivity(requireContext(),2,"$zhengsheng_cid",item.dateTime,"")
                    }
                }
            }

        val todayStr = sdf.format(System.currentTimeMillis())
        todayStamp = sdf.parse(todayStr).time
        endTime = todayStamp
        starTime = todayStamp - 31 * 3600 * 1000 * 24L

        getListData()
    }

    fun getListData(endTime:String?=null){
        val map = hashMapOf<String,Any>()
        catalogID?.let{
            map["catalogId"] = it
        }
        chaitiao_cid?.let{
            map["firstCatalogId"] = it
        }
        zhengsheng_cid?.let{
            map["secondCatalogId"] = it
        }
        endTime?.let{
            map["endTime"] = it
        }
        map["pageNumber"] = page
        map["pageSize"] = 10

        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .findNewsCastByDatePage(map)
            .enqueue(object: Callback<BaseDataListBean<SimulcastBean>>{
                override fun onResponse(
                    call: Call<BaseDataListBean<SimulcastBean>>,
                    response: Response<BaseDataListBean<SimulcastBean>>) {
                    freshLayout?.finishRefresh()
                    freshLayout?.finishLoadMore()
                    response.body()?.let{
                        closeStateView()
                        if (it.state == 200){
                            val data = it.data.pageRecords
                            freshLayout?.setEnableLoadMore(it.data.isHasNextPage)
                            if(page == 1 ){
                                if (data.size == 0) {
                                    showStateView(TYPE_NO_CONTENT, false)
                                }else {
                                    dataReady = true
                                    val targetData = sdf.parse(data[0].dateTime)
                                    val calendar = Calendar.getInstance()
                                    buildTime(targetData.time)
                                    calendar.time = targetData
                                    year = calendar.get(Calendar.YEAR)
                                    month = calendar.get(Calendar.MONTH)+1
                                    day = calendar.get(Calendar.DAY_OF_MONTH)

                                    simulcastAdapter?.setNewData(data)
                                }
                            }else{
                                simulcastAdapter?.addData(data)
                            }
                        }else{
                            showStateView(TYPE_NO_CONTENT, false)
                        }
                    }


                }

                override fun onFailure(call: Call<BaseDataListBean<SimulcastBean>>, t: Throwable) {

                }

            })
    }


    fun openDateSelector() {
        var sheet = SimulcastCalendarSheet()
        val b = Bundle()
        b.putString("NID", chaitiao_cid)
        b.putInt("year", year)
        b.putInt("month", month)
        b.putInt("day", day)
        sheet!!.arguments = b
        sheet?.call = object : SimulcastCalendarSheet.SelectedCall {
            override fun onSelected(calendar: com.haibin.calendarview.Calendar?) {
                calendar?.let {
                    year = it.year
                    month = it.month
                    day = it.day
                    buildTime(it.timeInMillis)
                    showStateView(BaseBackActivity.TYPE_LOADING, false)
                    getListData(sdf.format(Date(it.timeInMillis)))
                }
            }
        }
        sheet?.show(childFragmentManager, "")
    }



    private fun buildTime(targetTime: Long) {
        this.targetTime = targetTime
        // 如果目标日期+15天大于了今天 开始时间就取 今天往前推31天
        if (targetTime + 15 * 3600 * 1000 * 24L > todayStamp) {
            starTime = todayStamp - 31 * 3600 * 1000 * 24L
            //结束时间一定要多出3天 否则不能居中
            val tempEndTime = targetTime + 3 * 3600 * 1000 * 24L
            if (tempEndTime > todayStamp) {
                endTime = tempEndTime

            } else {
                endTime = todayStamp
            }
        } else {
            //这种情况前后取15天
            starTime = targetTime - 15 * 3600 * 1000 * 24L
            endTime = targetTime + 15 * 3600 * 1000 * 24L
        }
        targetIndex = ((targetTime - starTime) / (3600 * 1000 * 24L)).toInt()
    }


    override fun onRefresh(refreshLayout: RefreshLayout) {
        page = 1
        getListData()
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        page++
        getListData()
    }

    override fun choosed() {
        super.choosed()
        if (isAdded){

        }
    }
    var dataReady: Boolean = false

    fun app_jhapp_home_subtab_content_imp() {
        if (!dataReady) return
        if (rvSimulcast != null) {
            rvSimulcast.removeCallbacks(app_jhapp_home_subtab_content_impRunable)
            rvSimulcast.postDelayed(
                app_jhapp_home_subtab_content_impRunable,
                TXReportManager.EXPOSURE_DELAY
            )
        }
    }

    private val app_jhapp_home_subtab_content_impRunable = Runnable {
        getExecutorService().execute {
            try {
                for (i in 0 until scroll.childCount) {
                    val view = scroll.getChildAt(i)
                    if (getVisibility(view)){
                        exposureArticles?.forEachIndexed { index, articleItem ->
                            CDPTrackReportManager.getInstance().NewsRPExpose(index, articleItem)
                        }
                    }
                }

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun getExposureArticles(): MutableList<ArticleItem>? {
        val data = simulcastAdapter?.data
        var dataList = ArrayList<ArticleItem>()
        data?.forEachIndexed { index, simulcastBean ->
            if (simulcastBean.newsCastList.isNotEmpty()){
                val newsCast = simulcastBean.newsCastList[0]
                val articleItem = ArticleItem()
                articleItem.id = newsCast.id
                articleItem.type = newsCast.type
                articleItem.catalogId = newsCast.catalogId
                articleItem.logo = newsCast.logo
                articleItem.title = newsCast.title
                articleItem.publishdate_format = newsCast.publishDate
                articleItem.publishdate = newsCast.publishDate
                articleItem.referName = newsCast.referName
                articleItem.Author = newsCast.author
                articleItem.authorId = newsCast.authorId
                articleItem.authorNickName = newsCast.authorNickName
                dataList.add(articleItem)
            }

            if (simulcastBean.latestFlag == "Y"){//最新一条显示全部
                if (simulcastBean.firstSplitList.isNotEmpty()){
                    simulcastBean.firstSplitList.forEachIndexed { index, bean ->
                        val referName  = if (TextUtils.isEmpty(bean.referName))
                           resources.getString(R.string.app_name) else bean.referName
                        val date = if (TextUtils.isEmpty(bean.publishRelativeTime)) {
                            bean.publishDate
                        }else bean.publishRelativeTime
                        val articleItem = ArticleItem()
                        articleItem.id = bean.id
                        articleItem.type = bean.type
                        articleItem.catalogId = bean.catalogId
                        articleItem.publishdate = date
                        articleItem.referName = referName
                        articleItem.title = bean.title
                        articleItem.logo = bean.logo
                        articleItem.Author = bean.author
                        articleItem.authorId = bean.authorId
                        articleItem.authorNickName = bean.authorNickName
                        dataList.add(articleItem)
                    }

                }

            }else {
                if (simulcastBean.firstSplitList.isNotEmpty()){
                    simulcastBean.firstSplitList.forEachIndexed { index, bean ->
                        val referName  = if (TextUtils.isEmpty(bean.referName))
                            resources.getString(R.string.app_name) else bean.referName
                        val date = if (TextUtils.isEmpty(bean.publishRelativeTime)) {
                            bean.publishDate
                        }else bean.publishRelativeTime
                        val articleItem = ArticleItem()
                        articleItem.id = bean.id
                        articleItem.type = bean.type
                        articleItem.catalogId = bean.catalogId
                        articleItem.publishdate = date
                        articleItem.referName = referName
                        articleItem.title = bean.title
                        articleItem.logo = bean.logo
                        articleItem.Author = bean.author
                        articleItem.authorId = bean.authorId
                        articleItem.authorNickName = bean.authorNickName
                        dataList.add(articleItem)
                    }

                }

                if (simulcastBean.secondSplitList.isNotEmpty()) {
                    simulcastBean.secondSplitList.forEachIndexed { index, bean ->
                        val referName  = if (TextUtils.isEmpty(bean.referName))
                            resources.getString(R.string.app_name) else bean.referName
                        val date = if (TextUtils.isEmpty(bean.publishRelativeTime)) {
                            bean.publishDate
                        }else bean.publishRelativeTime
                        val articleItem = ArticleItem()
                        articleItem.id = bean.id
                        articleItem.type = bean.type
                        articleItem.catalogId = bean.catalogId
                        articleItem.publishdate = date
                        articleItem.referName = referName
                        articleItem.title = bean.title
                        articleItem.logo = bean.logo
                        articleItem.Author = bean.author
                        articleItem.authorId = bean.authorId
                        articleItem.authorNickName = bean.authorNickName
                        dataList.add(articleItem)
                    }


                }

            }
        }

        return dataList
    }

    override fun getExposureComponentItem(): ComponentItem? {
        return  null
    }

}